<template>
  <div class="search-container">
    <div class="container">
      <!-- 搜索结果标题 -->
      <div class="search-header">
        <h1>搜索结果："{{ keyword }}"</h1>
        <p v-if="loading">正在搜索中...</p>
        <p v-else-if="searchResults.length === 0 && keyword">未找到相关视频</p>
      </div>

      <!-- 搜索结果列表 -->
      <div class="video-list" v-if="!loading">
        <el-card 
          v-for="video in searchResults" 
          :key="video.video_id"
          class="video-card"
          @click="goToVideoDetail(video.video_id)"
        >
          <div class="video-cover">
            <img 
              :src="video.video_cover || '/placeholder.svg?size=300x180'" 
              :alt="video.video_title"
              class="cover-image"
            >
            <span class="view-count"><el-icon><View /></el-icon> {{ video.view_count || 0 }}</span>
          </div>
          <div class="video-info">
            <h3 class="video-title">{{ video.video_title }}</h3>
            <div class="video-meta">
              <span class="author">{{ getUserName(video.user_id) }}</span>
              <div class="video-stats">
                <span><el-icon><StarFilled /></el-icon> {{ video.like_count || 0 }}</span>
                <span><el-icon><ChatDotRound /></el-icon> {{ getCommentCount(video.video_id) }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 加载中 -->
      <div v-if="loading" class="loading-container">
        <el-empty description="正在搜索中..." />
      </div>

      <!-- 无结果 -->
      <div v-if="!loading && searchResults.length === 0 && keyword" class="empty-container">
        <el-empty description="未找到相关视频" />
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useVideoStore } from '../store/videoStore'
import { useUserStore } from '../store/userStore'
import { View, StarFilled, ChatDotRound } from '@element-plus/icons-vue'
import { ElCard, ElEmpty } from 'element-plus'

export default {
  name: 'SearchView',
  components: {
    ElCard,
    ElEmpty,
    View,
    StarFilled,
    ChatDotRound
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const videoStore = useVideoStore()
    const userStore = useUserStore()
    const loading = ref(false)
    const searchResults = ref([])
    const commentsMap = ref({})

    // 从路由参数中获取搜索关键词
    const keyword = computed(() => route.query.keyword || '')

    // 加载视频列表
    const loadVideos = async () => {
      if (!keyword.value) {
        searchResults.value = []
        return
      }
      
      loading.value = true
      try {
        // 使用videoStore中的搜索方法
        const results = await videoStore.searchVideos(keyword.value)
        searchResults.value = results
        
        // 加载评论数
        await loadCommentsCount()
      } catch (error) {
        console.error('搜索视频失败:', error)
        searchResults.value = []
      } finally {
        loading.value = false
      }
    }

    // 加载评论数
    const loadCommentsCount = async () => {
      try {
        const comments = await fetch('http://localhost:3000/comments')
        const data = await comments.json()
        // 统计每个视频的评论数
        data.forEach(comment => {
          if (!commentsMap.value[comment.video_id]) {
            commentsMap.value[comment.video_id] = 0
          }
          commentsMap.value[comment.video_id]++
        })
      } catch (error) {
        console.error('加载评论数失败:', error)
      }
    }

    // 获取用户名
    const getUserName = (userId) => {
      try {
        // 简单处理，实际应该从用户数据中获取
        const names = ['张三', '李四', '王五', '赵六', '测试用户1', '测试用户2']
        return names[userId - 1] || '未知用户'
      } catch (error) {
        return '未知用户'
      }
    }

    // 获取评论数
    const getCommentCount = (videoId) => {
      return commentsMap.value[videoId] || 0
    }

    // 跳转到视频详情
    const goToVideoDetail = (videoId) => {
      router.push(`/video/${videoId}`)
    }

    // 监听关键词变化
    watch(() => route.query.keyword, () => {
      loadVideos()
    })

    // 组件挂载时加载视频
    onMounted(() => {
      loadVideos()
    })

    return {
      keyword,
      loading,
      searchResults,
      getUserName,
      getCommentCount,
      goToVideoDetail
    }
  }
}
</script>

<style scoped>
.search-container {
  padding: 20px 0;
  background-color: #1a1a1a;
  min-height: calc(100vh - 60px);
}

.container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.search-header {
  margin-bottom: 30px;
}

.search-header h1 {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 10px;
  color: #ffffff;
}

.search-header p {
  font-size: 14px;
  color: #909399;
}

.video-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.video-card {
  height: 100%;
  cursor: pointer;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
  background-color: #2c2c2c !important;
  border-color: #404040 !important;
}

.video-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.6);
}

.video-cover {
  position: relative;
  width: 100%;
  padding-top: 56.25%; /* 16:9 aspect ratio */
  overflow: hidden;
}

.cover-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.view-count {
  position: absolute;
  bottom: 8px;
  right: 8px;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.video-info {
  padding: 12px 0;
}

.video-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 8px;
  line-height: 1.4;
  color: #ffffff;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.video-meta {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.author {
  font-size: 14px;
  color: #909399;
}

.video-stats {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #909399;
}

.video-stats span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.loading-container,
.empty-container {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #2c2c2c;
  border-radius: 8px;
  border: 1px solid #404040;
}

@media (max-width: 768px) {
  .video-list {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  }
  
  .search-header h1 {
    font-size: 20px;
  }
}

@media (max-width: 480px) {
  .video-list {
    grid-template-columns: 1fr;
  }
}
</style>